package org.budo.lock.distributed.service.redis;

import org.budo.lock.distributed.api.service.DistributedLockService;
import org.budo.support.assertion.Assert;

import redis.clients.jedis.Jedis;

/**
 * @author limingwei2
 */
public class RedisDistributedLockService extends AbstractRedisDistributedLockService implements DistributedLockService {
    public String tryLock(String target, String caller) {
        Assert.notEmpty(target, "target is null");

        synchronized (target) { // 在同一个虚拟机里串行，降低redis负载
            Jedis jedis = null;
            try {
                jedis = this.getJedis();
                long acquired = jedis.setnx(target, caller);
                if (1 == acquired) { // 加锁成功
                    jedis.expire(target, this.getLockExpireSeconds()); // 如果锁释放失败，会在指定时间内自动过期
                    return null;
                }

                return jedis.get(target);
            } finally {
                this.returnJedis(jedis);
            }
        }
    }

    public void unLock(String target) {
        Jedis jedis = null;
        try {
            jedis = this.getJedis();
            jedis.del(target);
        } finally {
            this.returnJedis(jedis);
        }
    }
}